<template>
  <div class="customer-service-management">
    <el-card class="box-card">
      <!-- 搜索条件区域 -->
      <el-form 
        :inline="true" 
        :model="searchForm" 
        class="search-form"
        size="mini"
      >
        <el-form-item label="客服ID">
          <el-input 
            v-model="searchForm.id" 
            placeholder="请输入ID" 
            clearable
            style="width: 120px"
          ></el-input>
        </el-form-item>

        <el-form-item label="客服昵称">
          <el-input 
            v-model="searchForm.nickname" 
            placeholder="请输入昵称" 
            clearable
            style="width: 160px"
          ></el-input>
        </el-form-item>

        <el-form-item label="性别">
          <el-select 
            v-model="searchForm.serviceSex" 
            placeholder="请选择" 
            clearable
            style="width: 120px"
          >
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="地址">
          <el-select 
            v-model="searchForm.addressName" 
            placeholder="请选择" 
            clearable
            style="width: 160px"
          >
            <el-option 
              v-for="item in addressList" 
              :key="item.id" 
              :label="item.addressName" 
              :value="item.addressName"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item class="search-btns">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>

      <!-- 客服列表表格 -->
      <el-table 
        :data="serviceList" 
        style="width: 100%" 
        v-loading="loading"
        border
        stripe
        size="mini"
      >
        <el-table-column prop="id" label="客服ID" width="80" align="center"></el-table-column>
        <!-- <el-table-column prop="serviceAvatar" label="头像" width="80" align="center">
          <template slot-scope="scope">
            <el-avatar 
              v-if="scope.row.serviceAvatar" 
              :src="scope.row.serviceAvatar" 
              size="small"
            ></el-avatar>
            <el-avatar v-else size="small">无</el-avatar>
          </template>
        </el-table-column> -->
        <el-table-column prop="serviceNickname" label="客服昵称" align="center"></el-table-column>
        <el-table-column prop="serviceName" label="真实姓名" align="center"></el-table-column>
        <el-table-column prop="serviceSex" label="性别" align="center"></el-table-column>
        <el-table-column prop="serviceEmail" label="邮箱" align="center"></el-table-column>
        <el-table-column prop="serviceHandle" label="处理次数" align="center"></el-table-column>
        <el-table-column prop="serviceStatus" label="在线状态" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.serviceStatus === 1 ? 'success' : 'info'" size="mini">
              {{ scope.row.serviceStatus === 1 ? '在线' : '离线' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="addressName" label="地址" align="center"></el-table-column>
        <el-table-column prop="userTelephone" label="联系电话" align="center"></el-table-column>
        <el-table-column prop="userStatus" label="状态" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.userStatus === 0 ? 'success' : 'danger'" size="mini">
              {{ scope.row.userStatus === 0 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center"></el-table-column>
        <el-table-column label="操作" width="260" align="center">
          <template slot-scope="scope">
            <el-button 
              size="mini" 
              type="text" 
              @click="handleViewDetail(scope.row)"
              icon="el-icon-view"
            >
              详情
            </el-button>
            <el-button 
              size="mini" 
              type="text" 
              @click="handleEdit(scope.row)"
              icon="el-icon-edit"
            >
              编辑
            </el-button>
            <el-button 
              size="mini" 
              type="text" 
              @click="handleChangeStatus(scope.row)"
              :icon="scope.row.userStatus === 0 ? 'el-icon-lock' : 'el-icon-unlock'"
              :class="scope.row.userStatus === 0 ? 'lock-btn' : 'unlock-btn'"
            >
              {{ scope.row.userStatus === 0 ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              size="mini" 
              type="text" 
              @click="handleDelete(scope.row)"
              icon="el-icon-delete"
              class="delete-btn"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="pagination"
        size="mini"
      ></el-pagination>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog 
      :title="dialogTitle" 
      :visible.sync="dialogVisible" 
      width="50%"
      center
      size="mini"
    >
      <el-form 
        :model="formData" 
        label-width="120px" 
        ref="formRef"
        :rules="formRules"
        size="mini"
      >
        <el-form-item label="客服ID" v-if="formData.id">
          <el-input v-model="formData.id" disabled></el-input>
        </el-form-item>
        
        <el-form-item label="用户ID" prop="userId" v-if="formData.id">
          <el-input
            v-model="formData.userId"
            placeholder="请输入关联用户ID"
            :disabled="!!formData.id"
          ></el-input>
        </el-form-item>

        <!-- <el-form-item label="租户ID" prop="tenantId" v-if="!formData.id">
          <el-input v-model.number="formData.tenantId" placeholder="请输入租户ID"></el-input>
        </el-form-item> -->

        <el-form-item label="手机号" prop="userTelephone" v-if="!formData.id">
          <el-input v-model="formData.userTelephone" placeholder="请输入手机号"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="userPassword" v-if="!formData.id">
          <el-input v-model="formData.userPassword" placeholder="请输入密码" show-password></el-input>
        </el-form-item>

        <!-- <el-form-item label="处理次数" prop="serviceHandle" v-if="!formData.id">
          <el-input v-model="formData.serviceHandle" placeholder="请输入处理次数"></el-input>
        </el-form-item> -->

        <el-form-item label="真实姓名" prop="serviceName">
          <el-input v-model="formData.serviceName" placeholder="请输入真实姓名"></el-input>
        </el-form-item>

        <el-form-item label="客服昵称" prop="serviceNickname">
          <el-input v-model="formData.serviceNickname" placeholder="请输入客服昵称"></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="serviceSex">
          <el-select v-model="formData.serviceSex" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="邮箱" prop="serviceEmail">
          <el-input v-model="formData.serviceEmail" placeholder="请输入邮箱"></el-input>
        </el-form-item>

        <el-form-item label="地址" prop="addressId">
          <el-select v-model="formData.addressId" placeholder="请选择地址">
            <el-option
              v-for="item in addressList"
              :key="item.id"
              :label="item.addressName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="头像" prop="serviceAvatar">
          <el-input v-model="formData.serviceAvatar" placeholder="请输入头像URL"></el-input>
        </el-form-item> -->

        <!-- <el-form-item label="在线状态" prop="serviceStatus">
          <el-switch
            v-model="formData.serviceStatus"
            :active-value="1"
            :inactive-value="0"
            active-text="在线"
            inactive-text="离线">
          </el-switch>
        </el-form-item> -->

        <!-- <el-form-item label="创建人" prop="creator" v-if="!formData.id">
          <el-input v-model="formData.creator" placeholder="请输入创建人"></el-input>
        </el-form-item> -->
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="saveForm" size="mini">确 定</el-button>
      </span>
    </el-dialog>
    
    <!-- 客服详细信息弹窗 -->
    <el-dialog 
      title="客服详细信息" 
      :visible.sync="detailDialogVisible" 
      width="60%"
      destroy-on-close
    >
      <el-row :gutter="20">
        <!-- 用户信息 -->
        <el-col :span="24">
          <h3>用户信息</h3>
          <el-descriptions :column="2" border size="mini" v-if="detailData">
            <el-descriptions-item label="用户ID">{{ detailData.userId || '-' }}</el-descriptions-item>
            <el-descriptions-item label="客服手机号">{{ detailData.userTelephone || '-' }}</el-descriptions-item>
            <el-descriptions-item label="用户状态">
              <el-tag :type="detailData.userStatus === 0 ? 'success' : 'danger'" size="mini">
                {{ detailData.userStatus === 0 ? '启用' : '禁用' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="用户创建时间">{{ detailData.userCreateTime || '-' }}</el-descriptions-item>
          </el-descriptions>
        </el-col>
        
        <!-- 客服信息 -->
        <el-col :span="24" style="margin-top:15px">
          <h3>客服信息</h3>
          <el-descriptions :column="2" border size="mini" v-if="detailData">
            <el-descriptions-item label="客服ID">{{ detailData.id || '-' }}</el-descriptions-item>
            <el-descriptions-item label="客服昵称">{{ detailData.serviceNickname || '-' }}</el-descriptions-item>
            <el-descriptions-item label="真实姓名">{{ detailData.serviceName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="性别">{{ detailData.serviceSex === 0 ? '男' : '女' }}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{ detailData.serviceEmail || '-' }}</el-descriptions-item>
            <el-descriptions-item label="处理次数">{{ detailData.serviceHandle || '-' }}</el-descriptions-item>
            <el-descriptions-item label="头像">
              <el-image 
                v-if="detailData.serviceAvatar" 
                :src="detailData.serviceAvatar" 
                style="width: 50px; height: 50px"
                fit="cover"
                :preview-src-list="[detailData.serviceAvatar]">
              </el-image>
              <span v-else>无</span>
            </el-descriptions-item>
            <el-descriptions-item label="在线状态">
              <el-tag :type="detailData.serviceStatus === 1 ? 'success' : 'info'" size="mini">
                {{ detailData.serviceStatus === 1 ? '在线' : '离线' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ detailData.createTime || '-' }}</el-descriptions-item>
          </el-descriptions>
        </el-col>
        
        <!-- 地址信息 -->
        <el-col :span="24" style="margin-top:15px">
          <h3>地址信息</h3>
          <el-descriptions :column="1" border size="mini" v-if="detailData">
            <el-descriptions-item label="地址">{{ detailData.addressName || '-' }}</el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false" size="mini">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import adminApi from '@/http/adminApi.js';

export default {
  name: 'CustomerServiceManagement',
  data() {
    return {
      addressList: [],
      searchForm: {
        id: '',
        nickname: '',
        serviceSex: '',
        addressName: '',
        tenantId: 1
      },
      serviceList: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      detailDialogVisible: false,
      dialogTitle: '',
      formData: {
        id: null,
        userId: '',
        tenantId: 1,
        userTelephone: '',
        userPassword: '',
        serviceAvatar: '',
        serviceSex: '男',
        serviceName: '',
        serviceNickname: '',
        serviceEmail: '',
        addressId: null,
        serviceHandle: '0',
        serviceStatus: 1,
        creator: 'admin'
      },
      detailData: null,
      formRules: {
        userId: [
          { required: true, message: '请输入用户ID', trigger: 'blur' }
        ],
        tenantId: [
          { required: true, message: '请输入租户ID', trigger: 'blur' },
          { type: 'number', message: '租户ID必须为数字', trigger: 'blur' }
        ],
        userTelephone: [
          { required: true, message: '请输入手机号', trigger: 'blur' }
        ],
        userPassword: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        serviceName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' }
        ],
        serviceNickname: [
          { required: true, message: '请输入客服昵称', trigger: 'blur' }
        ],
        serviceSex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        serviceEmail: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
        ],
        addressId: [
          { required: true, message: '请选择地址', trigger: 'change' }
        ],
        serviceHandle: [
          { required: true, message: '请输入处理次数', trigger: 'blur' }
        ],
        creator: [
          { required: true, message: '请输入创建人', trigger: 'blur' }
        ]
      }
    };
  },
  mounted() {
    this.initData();
  },
  methods: {
    async initData() {
      try {
        await this.fetchAddressList();
        await this.fetchServiceList();
      } catch (error) {
        this.$message.error('页面初始化失败');
      }
    },

    async fetchAddressList() {
      try {
        const res = await adminApi.getAddressList();
        if (res.code === 200) {
          this.addressList = res.data || [];
        }
      } catch (error) {
        this.$message.error('获取地址列表失败');
      }
    },

    async fetchServiceList() {
      this.loading = true;
      try {
        const sexMap = { '男': 0, '女': 1 };
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          ...this.searchForm,
          serviceSex: this.searchForm.serviceSex ? sexMap[this.searchForm.serviceSex] : null
        };
        const res = await adminApi.getCustomerServiceList(params);
        if (res.code === 200) {
          this.serviceList = (res.data.list || []).map(item => ({
            ...item,
            serviceSex: item.serviceSex === 0 ? '男' : '女'
          }));
          this.total = res.data.total || 0;
        } else {
          this.$message.error(res.message || '获取客服列表失败');
        }
      } catch (error) {
        this.$message.error('获取客服列表异常');
      } finally {
        this.loading = false;
      }
    },

    handleSearch() {
      this.currentPage = 1;
      this.fetchServiceList();
    },

    resetSearch() {
      this.searchForm = {
        id: '',
        nickname: '',
        serviceSex: '',
        addressName: '',
        tenantId: 1
      };
      this.handleSearch();
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchServiceList();
    },

    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchServiceList();
    },

    handleAdd() {
      this.dialogTitle = '新增客服';
      this.formData = {
        id: null,
        userId: '',
        tenantId: 1,
        userTelephone: '',
        userPassword: '',
        serviceAvatar: '',
        serviceSex: '男',
        serviceName: '',
        serviceNickname: '',
        serviceEmail: '',
        addressId: null,
        serviceHandle: '0',
        serviceStatus: 1,
        creator: 'admin'
      };
      this.dialogVisible = true;
    },

    async handleViewDetail(row) {
      this.loading = true;
      try {
        const res = await adminApi.getCustomerServiceDetailAll({ id: row.id });
        if (res.code === 200 && res.data) {
          this.detailData = res.data;
          this.detailDialogVisible = true;
        } else {
          this.$message.error(res.message || '获取详情失败');
        }
      } catch (error) {
        this.$message.error('获取详情异常');
      } finally {
        this.loading = false;
      }
    },

    async handleEdit(row) {
      this.dialogTitle = '编辑客服';
      this.loading = true;
      try {
        const res = await adminApi.getCustomerServiceDetail({ id: row.id });
        if (res.code === 200 && res.data) {
          this.formData = {
            ...res.data,
            serviceSex: res.data.serviceSex === 0 ? '男' : '女',
            serviceStatus: res.data.serviceStatus || 0, // 确保服务状态正确设置
            tenantId: 1
          };
          // 查找地址列表中匹配的地址ID
          if (res.data.addressName) {
            const matchedAddress = this.addressList.find(address => address.addressName === res.data.addressName);
            if (matchedAddress) {
              this.formData.addressId = matchedAddress.id;
            }
          }
          this.dialogVisible = true;
        }
      } catch (error) {
        this.$message.error('获取详情失败');
      } finally {
        this.loading = false;
      }
    },

    async saveForm() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        const submitData = {
          ...this.formData,
          serviceSex: this.formData.serviceSex === '男' ? 0 : 1
        };

        this.loading = true;
        try {
          let res;
          if (this.formData.id) {
            // 调用更新客服信息接口
            res = await adminApi.updateCustomerService({
              id: this.formData.id,
              userId: this.formData.userId,
              serviceName: this.formData.serviceName,
              serviceNickname: this.formData.serviceNickname,
              serviceSex: submitData.serviceSex,
              serviceEmail: this.formData.serviceEmail,
              addressId: this.formData.addressId,
              serviceAvatar: this.formData.serviceAvatar,
              serviceStatus: this.formData.serviceStatus
            });
          } else {
            // 新增客服，使用新的接口参数
            res = await adminApi.addCustomerService({
              tenantId: this.formData.tenantId,
              userTelephone: this.formData.userTelephone,
              userPassword: this.formData.userPassword,
              serviceName: this.formData.serviceName,
              serviceNickname: this.formData.serviceNickname,
              serviceSex: submitData.serviceSex,
              serviceEmail: this.formData.serviceEmail,
              addressId: this.formData.addressId,
              serviceHandle: this.formData.serviceHandle,
              serviceAvatar: this.formData.serviceAvatar,
              serviceStatus: this.formData.serviceStatus,
              creator: this.formData.creator
            });
          }
          
          if (res.code === 200) {
            this.$message.success(this.formData.id ? '修改成功' : '新增成功');
            this.dialogVisible = false;
            this.fetchServiceList();
          } else {
            this.$message.error(res.message || '操作失败');
          }
        } catch (error) {
          this.$message.error('操作异常');
        } finally {
          this.loading = false;
        }
      });
    },

    async handleDelete(row) {
      try {
        await this.$confirm('确定要删除该客服吗？', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        this.loading = true;
        const res = await adminApi.deleteCustomerService({ id: row.id });
        if (res.code === 200) {
          this.$message.success('删除成功');
          this.fetchServiceList();
        } else {
          this.$message.error(res.message || '删除失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除异常');
        }
      } finally {
        this.loading = false;
      }
    },

    // 状态切换方法
    async handleChangeStatus(row) {
      const newStatus = row.userStatus === 0 ? 1 : 0;
      const statusText = newStatus === 0 ? '启用' : '禁用';
      
      try {
        await this.$confirm(`确定要${statusText}该客服吗？`, '确认操作', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        this.loading = true;
        const res = await adminApi.updateCustomerServiceStatus({
          id: row.id,
          userStatus: newStatus
        });
        
        if (res.code === 200) {
          this.$message.success(`${statusText}成功`);
          this.fetchServiceList();
        } else {
          this.$message.error(res.message || `${statusText}失败`);
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('操作异常');
        }
      } finally {
        this.loading = false;
      }
    }
  }
};
</script>

<style scoped>
.search-form {
  margin: 10px 0 20px;
  padding: 10px 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
.delete-btn {
  color: #f56c6c;
}
.lock-btn {
  color: #e6a23c;
}
.unlock-btn {
  color: #67c23a;
}
</style>